package com.github.tvbox.osc.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.lifecycle.ViewModelProvider
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.tvbox.osc.R
import com.github.tvbox.osc.base.BaseLazyFragment
import com.github.tvbox.osc.ui.activity.CollectActivity
import com.github.tvbox.osc.ui.activity.DetailActivityKt
import com.github.tvbox.osc.ui.activity.HistoryActivity
import com.github.tvbox.osc.ui.activity.LivePlayActivity
import com.github.tvbox.osc.ui.activity.PushActivity
import com.github.tvbox.osc.ui.activity.SearchActivity
import com.github.tvbox.osc.ui.activity.SettingActivity
import com.github.tvbox.osc.ui.adapter.HomeHotVodAdapter
import com.github.tvbox.osc.ui.tv.widget.LoadMoreView
import com.github.tvbox.osc.util.FastClickCheckUtil
import com.github.tvbox.osc.viewmodel.SourceViewModel
import com.owen.tvrecyclerview.widget.TvRecyclerView
import com.owen.tvrecyclerview.widget.V7GridLayoutManager
import io.github.source.media.bean.MediaBean
import io.github.source.media.bean.MediaCategory
import io.github.source.media.bean.MediaQuery
import io.github.source.media.bean.MediaResult

/**
 * @ClassName: UserFragmentKt
 * @Description: (首页)
 * @author: huangrongcai
 * @date: 2025/6/28
 *
 * @Copyright: 黄嵘才（HuangRc)
 */
class UserFragmentKt : BaseLazyFragment(), View.OnClickListener {
    private var sortData: MediaCategory? = null
    private lateinit var sourceViewModel: SourceViewModel
    private var gridAdapter: HomeHotVodAdapter? = null
    private var page = 1
    private var maxPage = 1
    private var isLoad = false
    private var tvLive: LinearLayout? = null
    private var tvSearch: LinearLayout? = null
    private var tvSetting: LinearLayout? = null
    private var tvHistory: LinearLayout? = null
    private var tvCollect: LinearLayout? = null
    private var tvPush: LinearLayout? = null

    companion object {
        @JvmStatic
        fun newInstance(data: MediaCategory): UserFragmentKt {
            return UserFragmentKt().apply {
                this.setData(data)
            }
        }
    }

    fun setData(sortData: MediaCategory) {
        this.sortData = sortData
    }

    override fun getLayoutResID(): Int {
        return R.layout.fragment_user
    }

    override fun init() {
        super.init()
        initViewModel()
    }

    override fun initData() {
        super.initData()
        initMediaData()
    }

    override fun initView() {
        super.initView()
        val gridView = findViewById<TvRecyclerView>(R.id.tvHotListForLine)
        gridView.layoutManager = V7GridLayoutManager(mContext, 5)
        gridView?.setHasFixedSize(true)

        gridAdapter = HomeHotVodAdapter()
        gridView?.setAdapter(gridAdapter)

        gridAdapter?.setOnLoadMoreListener(createLoadMoreListener())
        gridAdapter?.setOnItemClickListener(createItemClickListener())
        gridAdapter?.setOnItemLongClickListener(createItemLongClickListener())
        gridAdapter?.setLoadMoreView(LoadMoreView())

        tvLive = findViewById(R.id.tvLive)
        tvSearch = findViewById<LinearLayout>(R.id.tvSearch)
        tvSetting = findViewById<LinearLayout>(R.id.tvSetting)
        tvCollect = findViewById<LinearLayout>(R.id.tvFavorite)
        tvHistory = findViewById<LinearLayout>(R.id.tvHistory)
        tvPush = findViewById<LinearLayout>(R.id.tvPush)
        tvLive?.setOnClickListener(this)
        tvSearch?.setOnClickListener(this)
        tvSetting?.setOnClickListener(this)
        tvHistory?.setOnClickListener(this)
        tvPush?.setOnClickListener(this)
        tvCollect?.setOnClickListener(this)

    }

    private fun initViewModel() {
        sourceViewModel = ViewModelProvider(this).get(SourceViewModel::class.java)
        sourceViewModel.MediaBeanResult?.observe(
            this
        ) { result: MediaResult<List<MediaBean>?>? ->
            setMediaResultData(result)
            if (page > maxPage) {
                gridAdapter?.loadMoreEnd()
            } else {
                gridAdapter?.loadMoreComplete()
            }
        }
    }

    protected fun initMediaData() {
        showLoading()
        isLoad = false
        val query = obtainQuery()
        sourceViewModel.fetchMediaList(query)
    }

    override fun onClick(v: View) {
        FastClickCheckUtil.check(v)
        if (v.id == R.id.tvLive) {
            jumpActivity(LivePlayActivity::class.java)
        } else if (v.id == R.id.tvSearch) {
            jumpActivity(SearchActivity::class.java)
        } else if (v.id == R.id.tvSetting) {
            jumpActivity(SettingActivity::class.java)
        } else if (v.id == R.id.tvHistory) {
            jumpActivity(HistoryActivity::class.java)
        } else if (v.id == R.id.tvPush) {
            jumpActivity(PushActivity::class.java)
        } else if (v.id == R.id.tvFavorite) {
            jumpActivity(CollectActivity::class.java)
        }
    }
    fun obtainQuery(): MediaQuery? {
        val query = MediaQuery.obtain()
        if (sortData != null) {
            query.setId(sortData?.id)
        }
        query.page(page)
        query.setType(MediaQuery.TYPE_HOME)
        return query
    }

    private fun setMediaResultData(result: MediaResult<List<MediaBean>?>?) {
        if (result?.data?.isNotEmpty() == true) {
            showSuccess()
            if (isDataEmpty()) { //第一页（次）刷新
                isLoad = true
                gridAdapter?.setNewData(result.data)
            } else {
                gridAdapter?.addData(result.data!!)
            }
            page++
            maxPage = 999
        } else {
            if (isDataEmpty()) {
                showEmpty()
            } else {
                gridAdapter?.setEnableLoadMore(false)
            }
        }
    }

    private fun isDataEmpty(): Boolean {
        return gridAdapter?.data == null || gridAdapter?.data?.isEmpty() == true
    }

    private fun createLoadMoreListener(): BaseQuickAdapter.RequestLoadMoreListener {
        return BaseQuickAdapter.RequestLoadMoreListener {
            val query = obtainQuery()
            sourceViewModel.fetchMediaList(query)
        }
    }

    private fun createItemClickListener(): BaseQuickAdapter.OnItemClickListener? {
        return BaseQuickAdapter.OnItemClickListener { adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int ->
            FastClickCheckUtil.check(view)
            val video = gridAdapter?.data?.get(position)
            if (video != null) {
                val bundle = Bundle()
                bundle.putString("id", video.vodId)
                bundle.putString("sourceKey", video.siteKey)
                bundle.putString("title", video.vodName)
                if (video.vodId == null || video.vodId.isEmpty() || video.vodId.startsWith("msearch:")) {
                    jumpActivity(SearchActivity::class.java, bundle)
                } else {
                    jumpActivity(DetailActivityKt::class.java, bundle)
                }
            }
        }
    }

    private fun createItemLongClickListener(): BaseQuickAdapter.OnItemLongClickListener? {
        return BaseQuickAdapter.OnItemLongClickListener { adapter, view, position -> false }
    }
}